package com.utils.conmponentbase.base.viewmodel;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * MvvmDemo com.utils.conmponentbase.base.viewmodel
 * 2020-01-11 10:10
 * Note that only one observer is going to be notified of changes.
 */
public class SingleLiveEvent<T> extends MutableLiveData<T> {
    private final AtomicBoolean mPending = new AtomicBoolean(false);

    @MainThread
    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
        //Multiple observers registered but only one will be notified of changes.
        //注册了多个观察员，但只有一名观察员会收到更改通知
        super.observe(owner, pT -> {
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(pT);
            }
        });
    }

    @MainThread
    @Override
    public void setValue(T value) {
        mPending.set(true);
        super.setValue(value);
    }

    /**
     * 用于T为空的情况，以使通话更清晰。有T时调用 {@link #setValue(T)}
     */
    @MainThread
    public void call() {
        setValue(null);
    }
}
